local skel = fk.CreateSkill {
  name = "rmt__wangxin",
  tags = {Skill.Compulsory},
}

Fk:loadTranslationTable{
  ["rmt__wangxin"] = "王衅",
  [":rmt__wangxin"] = "锁定技，若你手牌恰好半数为黑色，则你装备区的牌无效；其他角色计算与你的距离-X（X为你装备区的牌数）；否则，准备与结束阶段，你须摸一张牌，再将X或三张牌均替换为【影】（X为西势力角色数）。",

  ["#rmt__wangxin-choice"] = "王衅：选择一个数字，将此数字张牌替换为等量张【影】",
  ["#rmt__wangxin-cards"] = "王衅：选择 %arg 张牌，替换为等量张【影】",
}

local U = require "packages.utility.utility"

--- 若你手牌恰好半数为黑色
---@param player Player
local function halfBlack(player)
  local hand = player:getCardIds("h")
  return #table.filter(hand, function (id)
    return Fk:getCardById(id).color == Card.Black
  end) == #hand / 2
end

skel:addEffect(fk.EventPhaseStart, {
  anim_type = "control",
  can_trigger = function (self, event, target, player, data)
    return target == player and player:hasSkill(skel.name) and not halfBlack(player)
    and (player.phase == Player.Start or player.phase == Player.Finish)
  end,
  on_use = function (self, event, target, player, data)
    local room = player.room
    player:drawCards(1, skel.name)
    if player.dead or player:isNude() then return end
    local cards = player:getCardIds("he")
    local x = #table.filter(room.alive_players, function (p)
      return p.kingdom == "west"
    end)
    local choices = {}
    if #cards >= 3 then table.insert(choices, 3) end
    if #cards >= x then table.insert(choices, x) end
    if #choices > 0 then
      choices = table.map(choices, tostring)
      local ch = room:askToChoice(player, {
        choices = choices, skill_name = skel.name, prompt = "#rmt__wangxin-choice",
      })
      local num = tonumber(ch) or 1
      cards = room:askToCards(player, {
        min_num = num, max_num = num, skill_name = skel.name, cancelable = false, include_equip = true,
        prompt = "#rmt__wangxin-cards:::" .. num,
      })
    end
    room:moveCardTo(cards, Card.Void, nil, fk.ReasonJustMove, skel.name, nil, true, player)
    if player.dead then return end
    room:obtainCard(player, U.getShade(room, #cards), true, fk.ReasonJustMove, player, skel.name)
  end,
})

skel:addEffect("distance", {
  correct_func = function (self, from, to)
    if to:hasSkill(skel.name) and halfBlack(to) then
      return - #to:getCardIds("e")
    end
  end,
})

skel:addEffect("invalidity", {
  invalidity_func = function (self, player, skill)
    return skill:isEquipmentSkill(player) and halfBlack(player) and player:hasSkill(skel.name, true)
  end,
  invalidity_attackrange = function (self, player, card) -- 无效攻击范围
    return halfBlack(player) and player:hasSkill(skel.name, true)
  end,
})


return skel
